package com.pucong.gitee.database.backup.business.unRelational.redis.util;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.pucong.gitee.database.backup.common.entity.redis.RedisConnect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class JschUtil {

    static JSch jsch;
    static Session session;

    public static void openSSH(RedisConnect connect) throws Exception {
        log.info("正在打开SSH通道...");
        if (null != session) {
            session.disconnect();
        }
        jsch = new JSch();
        if (StringUtils.isNoneBlank(connect.getSPkey())) {
            jsch.addIdentity(connect.getSPkey(), "");
        }
        session = jsch.getSession(connect.getSName(), connect.getSHost(), connect.getSPort());
        session.setTimeout(3000);
        if (StringUtils.isEmpty(connect.getSPkey())) {
            session.setPassword(connect.getSPass());
        }
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("userauth.gssapi-with-mic", "no");
        session.connect(3000);
        String rhost = connect.getRHost();
        if (rhost.equals(connect.getRHost())) {
            rhost = "127.0.0.1";
        }
        session.setPortForwardingL(55555, rhost, Integer.valueOf(connect.getRPort()));
        log.info("已成功打开SSH通道，SSH服务器版本：" + session.getServerVersion());
    }

    public static void closeSSH() {
        try {
            if (null != session) {
                session.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
    }

}
